<template>
  <div>
    <el-card>
      <el-row>
        <el-button
          type="primary"
          :icon="Plus"
          @click="toCreate()"
          v-button="['api:formula:formuladata:create']"
        >
          新增
        </el-button>
      </el-row>
      <el-row>
        <el-table
          :data="tableList"
          :border="true"
          style="width: 100%"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        >
          <el-table-column prop="formulaKey" label="公式" width="180" />
          <el-table-column prop="formulaName" label="公式" width="180" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                type="primary"
                :icon="EditPen"
                @click="toEdit(scope.row)"
                v-button="['api:formula:formuladata:update']"
              >
                修改
              </el-button>
              <el-popconfirm title="确定要删除这条数据?" @confirm="toDelete(scope.row)">
                <template #reference>
                  <el-button
                    type="danger"
                    :icon="Delete"
                    v-button="['api:formula:formuladata:delete']"
                  >
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row>
        <Pagination
          :total="search.total"
          v-model:pageIndex="search.pageIndex"
          v-model:pageSize="search.pageSize"
          @change="query()"
        ></Pagination>
      </el-row>
    </el-card>

    <!-- 新增和修改弹框 -->
    <el-dialog
      v-model="dialogVisible"
      title="公式"
      width="600"
      :draggable="true"
      :close-on-click-modal="false"
    >
      <el-form label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item prop="variable">
              <template #label>
                <div class="flex-y-center">
                  变量
                  <el-tooltip placement="bottom" effect="dark">
                    <template #content>点击变量填充公式</template>
                    <i-ep-QuestionFilled />
                  </el-tooltip>
                </div>
              </template>
              <template #default>
                <div class="el-form-item__content gap-2">
                  <div class="flex gap-2 flex-wrap flex-center">
                    <el-tag
                      :hit="false"
                      type="primary"
                      v-for="item in formulaVariableList"
                      @click="clickVariable(item)"
                    >
                      {{ item.variableName }}
                    </el-tag>
                  </div>
                  <div class="flex gap-2 flex-wrap flex-center">
                    <el-button type="danger" @click="deleteVariable()">删除</el-button>
                    <el-button type="warning" @click="clearVariable()">清空</el-button>
                  </div>
                </div>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="公式" prop="formulaName">
              <el-input placeholder="公式" v-model="form.formulaName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save()">保存</el-button>
        </div>
      </template>
      <el-dialog v-model="dialogConstant" title="常量" append-to-body>
        <el-input-number v-model="constantNum" />
        <template #footer>
          <div>
            <el-button @click="dialogConstant = false">取消</el-button>
            <el-button type="primary" @click="confirm()">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  Plus,
  Delete,
  EditPen,
  Search,
  Position,
  View,
  CircleCheck,
} from "@element-plus/icons-vue";
import FormulaDataApi, {
  FormulaDataEdit,
  FormulaDataModel,
  FormulaDataQuery,
} from "@/api/formula/formulaData";
import { EditEnum } from "@/enums/EditEnum";
import successMsg from "@/utils/successMsg";
import FormulaVariableApi, { FormulaVariableList } from "@/api/formula/formulaVariable";
import { FormulaVariableTypeEnum } from "@/enums/FormulaVariableTypeEnum";

const tableList = ref<FormulaDataModel[]>();

//查询条件
const search = reactive<FormulaDataQuery>({
  total: 0,
  pageIndex: 1, //第几页
  pageSize: 10, //每页多少条
});

onMounted(async () => {
  await query();
});

const query = async () => {
  const { dataList, totalCount } = await FormulaDataApi.query(search);
  search.total = totalCount;
  tableList.value = dataList;
};

const form = ref<FormulaDataEdit>();
const dialogVisible = ref(false);
const editType = ref<EditEnum>();
const formulaVariableList = ref<FormulaVariableList[]>();
const toEdit = async (row: FormulaDataEdit) => {
  editType.value = EditEnum.update;
  dialogVisible.value = true;
  form.value = { ...row };

  formulaVariableList.value = await FormulaVariableApi.queryFormulaVariable();
};

const toCreate = async () => {
  editType.value = EditEnum.create;
  dialogVisible.value = true;
  form.value = {
    formulaKey: "",
    formulaName: "",
    variableIdArray: [],
    formulaKeyArray: [],
    formulaNameArray: [],
  };

  formulaVariableList.value = await FormulaVariableApi.queryFormulaVariable();
};

const save = async () => {
  const { success, message } = await FormulaDataApi[EditEnum[editType.value]](form.value);
  successMsg(success, message, async () => {
    dialogVisible.value = false;
    await query();
  });
};

const toDelete = async (row: FormulaDataModel) => {
  const { success, message } = await FormulaDataApi.delete(row.id);
  successMsg(success, message, await query());
};

const constantNum = ref(0);
const constantTag = ref<FormulaVariableList>();
const dialogConstant = ref(false);
const clickVariable = (tag: FormulaVariableList) => {
  if (tag.variableType === FormulaVariableTypeEnum.Constant) {
    dialogConstant.value = true;
    constantTag.value = { ...tag };
  } else {
    setFormulaValue(tag);
  }
};

const confirm = () => {
  constantTag.value.variableKey = constantNum.value.toString();
  constantTag.value.variableName = constantNum.value.toString();
  setFormulaValue(constantTag.value);
  constantTag.value = {};
  dialogConstant.value = false;
};

const setFormulaValue = (tag: FormulaVariableList) => {
  form.value.formulaKey += tag.variableKey;
  form.value.formulaName += tag.variableName;
  form.value.variableIdArray.push(tag.id);
  form.value.formulaKeyArray.push(tag.variableKey);
  form.value.formulaNameArray.push(tag.variableName);
};

const deleteVariable = () => {
  form.value.variableIdArray.pop();
  form.value.formulaNameArray.pop();
  form.value.formulaKeyArray.pop();
  form.value.formulaName = form.value.formulaNameArray.join("");
  form.value.formulaKey = form.value.formulaKeyArray.join("");
};

const clearVariable = () => {
  form.value.variableIdArray = [];
  form.value.formulaNameArray = [];
  form.value.formulaKeyArray = [];
  form.value.formulaName = "";
  form.value.formulaKey = "";
};
</script>

<style lang="scss" scoped>
.el-tag:hover {
  cursor: pointer;
  border-color: var(--el-tag-hover-color);
}
</style>
